package cn.schoolwow.flow.monitor.module.initial.flow;

import cn.schoolwow.flow.monitor.entity.FlowLog;
import cn.schoolwow.flow.monitor.util.FlowMonitorUtil;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.domain.FlowDataFeature;
import cn.schoolwow.quickflow.dto.FlowContextDataRange;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class SetFlowLogFlow implements BusinessFlow {
    private Logger logger = LoggerFactory.getLogger(SetFlowLogFlow.class);

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        //记录流程日志
        FlowLog flowLog = new FlowLog();
        flowLog.setFlowId(flowContext.getId());
        flowLog.setName(flowContext.getFlowName());
        try {
            //保存请求数据
            {
                Map<String,Object> requestDataMap = flowContext.getRequestDataMap();
                flowLog.setRequestData(JSON.parseObject(JSON.toJSONString(requestDataMap, SerializerFeature.WriteClassName)));
            }
            //保存流程执行数据
            {
                Map<String,Object> flowExecuteDataMap = flowContext.getFlowExecuteDataMap();
                flowLog.setContextData(JSON.parseObject(JSON.toJSONString(flowExecuteDataMap)));
            }
            //保存流程全局数据
            {
                Map<String,Object> contextDataMap = flowContext.getContextDataMap();
                flowLog.setQuickFlowData(JSON.parseObject(JSON.toJSONString(contextDataMap)));
            }
            //保存流程配置数据
            {
                Map<String,Object> flowConfigDataMap = flowContext.getFlowConfigDataMap();
                flowLog.setFlowConfigData(JSON.parseObject(JSON.toJSONString(flowConfigDataMap)));
            }
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            flowContext.printFlowDataRange();
            flowLog.setException(FlowMonitorUtil.exception2String(e));
            flowLog.setExceptionMessage(e.getMessage());
        }

        flowLog.setFlowNameList(flowContext.getFlowArray().toJSONString());
        flowLog.setFlowTrace(flowContext.getFlowTrace());
        flowLog.setBrokenReason(flowContext.getBrokenReason());
        Exception e = flowContext.getFlowException();
        if(null!=e){
            flowLog.setException(FlowMonitorUtil.exception2String(e));
            flowLog.setExceptionMessage(e.getMessage());
        }
        Long startTime = (Long) flowContext.getData("__startTime");
        if(null!=startTime){
            long endTime = System.currentTimeMillis();
            flowLog.setConsumeTime(endTime-startTime);
        }
        flowContext.putInstanceData(flowLog, FlowContextDataRange.Flow, FlowDataFeature.TemporaryData);
    }

    @Override
    public String name() {
        return "设置流程日志对象";
    }

}
